<?php

namespace App\Controller\AdminApi;

use App\Base\BaseForm;
use App\Repository\AdminGroupRepository as Repository;
use App\Repository\AdminMenuRepository;

use App\Base\IRI;
use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\AdminGroup as Entity;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/admin/")
 */
class AdminGroupAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "AdminGroup";
    public $limit = 10;

    /**
     * @Route("AdminGroup/form",name="AdminGroupForm")
     */
    public function form(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        if (!$entity) {$entity = new Entity();}
        $BaseForm = new BaseForm(Entity::class);
        //表单选项

        $BaseForm->addText("name","名称")->ruleNotNull()->getData();
        $BaseForm->addText("role","角色")->ruleNotNull()->getData();
        $BaseForm->addList("menus","权限",[])->setName("AdminMenu")->getData();

        $entity = $this->toArray($entity);
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("AdminGroup/submit",name="AdminGroupSubmit",methods={"POST"})
     */
    public function submit(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
        if (!$entity) {$entity = new  Entity();}
        /**@var $AdminGroup Entity*/
        $AdminGroup = $this->updateEntity($data,Entity::class,$entity);
        $this->myEm()->persist($AdminGroup);$this->myEm()->flush();
        return $this->json_out(1,"保存成功","");
    }

    /**
     * @Route("AdminGroup/list",name="AdminGroupGetList")
     */
    public function getList(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "AdminGroup",
            'title'     => "列表",
            'header'     => ["id","name","role"],
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total*1,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * @Route("AdminGroup/delete",name="AdminGroupDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * @Route("AdminGroup/copy",name="AdminGroupCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("AdminGroup/search",name="AdminGroupGetList4EntitySelect")
     */
    public function getList4EntitySelect(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "User",
            'title'     => "列表",
            'header'     => ["id"],
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("AdminGroup/viewer",name="AdminGroupList4EntityViewer")
     */
    public function AdminGroupList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("AdminGroup/choice",name="AdminGroupList4ListChoice")
     */
    public function AdminGroupList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }
}
